package com.cos.service.jpush;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.ClientConfig;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.report.ReceivedsResult;

import com.cos.util.DateUtil;
import com.cos.util.PageData;
import com.google.gson.Gson;

/**
 * 
 * TODO 向用户推送消息
 * <p/>
 * 
 * @author <a href="mailto:Hoindbq@163.com">Yang</a>
 * @version Date: 2016年3月25日 下午7:47:57
 * @serial 1.0
 * @since 2016年3月25日 下午7:47:57
 */
@Service("pushMessage")
public class PushMessage {

	/**
	 * JPush REST API
	 */
	private static String jpushApi = "https://api.jpush.cn";

	/**
	 * APP MASTER_SECRET
	 */
	private static String MASTER_SECRET = "46460c38385a4018f85327ff";

	/**
	 * APP APP_KEY
	 */
	private static String APP_KEY = "f21d5f046dd2c7cc008fcd20";
	/**
	 * TEST
	 */
	private static final String appKey ="dd1066407b044738b6479275";
	private static final String masterSecret = "e8cc9a76d5b7a580859bcfa7";

	/**
	 * PLATFORM:推送消息平台设置
	 */
	public static String PLATFORM = "all";

	/**
	 * OPTIONS_TIME_TO_LIVE:离线消息保存时间
	 */
	public static long OPTIONS_TIME_TO_LIVE = 86400;

	/**
	 * OPTIONS_TIME_TO_LIVE:推送测试环境
	 */
	public static boolean OPTIONS_APNS_PRODUCTION = false;

	public static JPushClient jpushClient = null;

	/**
	 * @MethodName: getInstance
	 * @Description: 获取推送客户端对象实例
	 * @return
	 * @throws
	 */
	public  synchronized JPushClient getInstance() {

		ClientConfig config = ClientConfig.getInstance();
		config.setApnsProduction(OPTIONS_APNS_PRODUCTION);
		config.setTimeToLive(OPTIONS_TIME_TO_LIVE);
		config.setPushHostName(jpushApi);
		JPushClient jPushClient = new JPushClient(masterSecret, appKey, null,
				config);
		return jPushClient;
	}
		@Resource(name="pushdetailService")
		private PushDetailService pushDetailService;

	/**
	 * @throws cn.jpush.api.common.resp.APIRequestException
	 * @throws cn.jpush.api.common.resp.APIConnectionException
	 * @throws Exception
	 * @throws cn.jpush.api.common.resp.APIConnectionException
	 * 
	 * @MethodName: pushMsgBroadCast
	 * @Description: 推送广播消息【后台不记录广播消息】
	 * @param pushMessage
	 * @param title
	 * @param alert
	 * @return
	 * @throws
	 */
	public  String pushMsgBroadCast(PageData pd) throws Exception {
		PushResult reqResult = null;
		ReceivedsResult repResult = null ;
		int pushNumber  =  0 ;
		// 推送所有平台 Android, iOS, Windows Phone
		Platform platform = Platform.all();
		// 推送所有设备 （设备列表）支持别名、标签、注册ID、分群、广播
		// all为发送广播。可选设备（tag，tag_and，alias，registration_id）
		Audience audience = Audience.all();
		// 通知对象（推送的实体内容对象之一（另一个是“消息”Message））包含四种属性三个平台属性一个alert（alert,title,builder_id,extras）
		Notification notifcation = Notification.android(pd.getString("PUSH_CONTENT"),
				pd.getString("TITLE"), null);
		// 重构PushPayload
		PushPayload pushPayload = PushPayload.newBuilder()
				.setPlatform(platform).setAudience(audience)
				.setNotification(notifcation).build();
			reqResult = getInstance().sendPush(pushPayload);
			repResult = getInstance().getReportReceiveds(String.valueOf(reqResult.msg_id)) ;
			  List<ReceivedsResult.Received> list = new ArrayList<ReceivedsResult.Received>() ;
              list = repResult.received_list ;
              for(ReceivedsResult.Received var :list){
              		 pushNumber = var.android_received + var.ios_apns_sent + var.ios_msg_received + var.wp_mpns_sent ;
              }
			pd.put("PUSH_TIME", DateUtil.getTime());
			pd.put("ACCEPTSTATE", String.valueOf(pushNumber));
			pd.put("SUCCESS_STATE", reqResult.isResultOK());
			pd.put("PUSH_STATE", reqResult.getResponseCode()==200?0:1);
			pd.put("MASTER_CODE",String.valueOf(reqResult.msg_id));
			pd.put("RECEIVE_CODE", String.valueOf(reqResult.sendno));
			pushDetailService.save(pd) ;
			return new Gson().toJson(reqResult);
}
	
	/**
	 * @throws Exception 
	 * @throws cn.jpush.api.common.resp.APIRequestException
	 * @throws cn.jpush.api.common.resp.APIConnectionException
	 * 
	 * @MethodName: pushMsgToRegistrationId
	 * @Description: 【单个推送】推送消息到用户注册ID(deviceToken)
	 * @param pushMessage
	 * @param title
	 * @param alert
	 * @return
	 * @throws
	 */
	public String pushMsgToRegistrationId(PageData pd) throws Exception  {
		PushResult reqResult = null;
		ReceivedsResult repResult = null ;
		int pushNumber  =  0 ;
		// 推送所有平台 Android, iOS, Windows Phone
		Platform platform = Platform.all();
		// 【单个推送】推送消息到用户注册ID
		Audience audience = Audience.registrationId(pd
				.getString("REGISTRATION_ID"));
		// 通知对象
		Notification notifcation = Notification.android(pd.getString("alert"),
				pd.getString("title"), null);
		PushPayload pushPayload = PushPayload.newBuilder()
				.setPlatform(platform).setAudience(audience)
				.setNotification(notifcation).build();
		try {
			reqResult = getInstance().sendPush(pushPayload);
			repResult = getInstance().getReportReceiveds(String.valueOf(reqResult.msg_id)) ;
			  List<ReceivedsResult.Received> list = new ArrayList<ReceivedsResult.Received>() ;
              list = repResult.received_list ;
              for(ReceivedsResult.Received var :list){
              		 pushNumber = var.android_received + var.ios_apns_sent + var.ios_msg_received + var.wp_mpns_sent ;
              }
			
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}finally{
			//保存推送信息
			//pushDetail.setID(pd.getString("ID"));
			//pushDetail.setDeviceToken(pd.getString("REGISTRATION_ID"));
			/*pushDetail.setPUSH_TIME(DateUtil.getTime());
			pushDetail.setAcceptState(String.valueOf(pushNumber));
			pushDetail.setSUCCESS_STATE(reqResult.isResultOK());
			pushDetail.setPUSH_CONTENT(pd.getString("alert"));
			pushDetail.setPUSH_STATE(reqResult.getResponseCode()==200?0:1);
			pushDetail.setMASTER_CODE(String.valueOf(reqResult.msg_id));
			pushDetailService.save(pd);; */
			pd.put("PUSH_TIME", DateUtil.getTime());
			pd.put("ACCEPTSTATE", String.valueOf(pushNumber));
			pd.put("SUCCESS_STATE", reqResult.isResultOK());
			pd.put("PUSH_STATE", reqResult.getResponseCode()==200?0:1);
			pd.put("MASTER_CODE",String.valueOf(reqResult.msg_id));
			pd.put("RECEIVE_CODE", String.valueOf(reqResult.sendno));
			pushDetailService.save(pd) ;
			}
		return new Gson().toJson(reqResult);
	}

	/**
	 * @throws Exception 
	 * 
	 * @MethodName: pushMsgByTag
	 * @Description: 【单个推送】推送消息到用户标签(deviceToken)
	 * @param pushMessage
	 * @param title
	 * @param alert
	 * @return
	 * @throws
	 */
	public String pushMsgByTag(PageData pd) throws Exception {
		PushResult reqResult = null;
		ReceivedsResult repResult = null ;
		int pushNumber  =  0 ;
		Platform platform = Platform.all();
		Audience audience = Audience.tag(pd.getString("DeviceToken"));
		Notification notifcation = Notification.android(pd.getString("alert"),
				pd.getString("title"), null);
		PushPayload pushPayload = PushPayload.newBuilder()
				.setPlatform(platform).setAudience(audience)
				.setNotification(notifcation).build();
		try {
			reqResult = getInstance().sendPush(pushPayload);
			repResult = getInstance().getReportReceiveds(String.valueOf(reqResult.msg_id)) ;
			  List<ReceivedsResult.Received> list = new ArrayList<ReceivedsResult.Received>() ;
              list = repResult.received_list ;
              for(ReceivedsResult.Received var :list){
              		 pushNumber = var.android_received + var.ios_apns_sent + var.ios_msg_received + var.wp_mpns_sent ;
              }
			
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}finally{
			//保存推送信息
		/*	pushDetail.setID("585858585");
			pushDetail.setDeviceToken(pd.getString("REGISTRATION_ID"));
			pushDetail.setPUSH_TIME(DateUtil.getTime());
			pushDetail.setAcceptState(String.valueOf(pushNumber));
			pushDetail.setSUCCESS_STATE(reqResult.isResultOK());
			pushDetail.setPUSH_CONTENT(pd.getString("alert"));
			pushDetail.setPUSH_STATE(reqResult.getResponseCode()==200?0:1);
			pushDetail.setMASTER_CODE(String.valueOf(reqResult.msg_id));
			pushDetailService.save(pushDetail); */
			pd.put("PUSH_TIME", DateUtil.getTime());
			pd.put("ACCEPTSTATE", String.valueOf(pushNumber));
			pd.put("SUCCESS_STATE", reqResult.isResultOK());
			pd.put("PUSH_STATE", reqResult.getResponseCode()==200?0:1);
			pd.put("MASTER_CODE",String.valueOf(reqResult.msg_id));
			pd.put("RECEIVE_CODE", String.valueOf(reqResult.sendno));
			pushDetailService.save(pd) ;
		}
		
		return new Gson().toJson(reqResult);
	}

	/**
	 * @throws Exception 
	 * 
	 * @MethodName: pushMsgByAlias
	 * @Description: 【单个推送】推送消息到用户手机号别名(deviceToken)
	 * @param pushMessage
	 * @param title
	 * @param alert
	 * @return
	 * @throws
	 */
	public String pushMsgByAlias(PageData pd) throws Exception {
		PushResult reqResult = null;
		ReceivedsResult repResult = null ;
		int pushNumber  =  0 ;
		Platform platform = Platform.all();
		Audience audience = Audience.alias(pd.getString("DeviceToken"));
		Notification notifcation = Notification.android(pd.getString("alert"),
				pd.getString("title"), null);
		PushPayload pushPayload = PushPayload.newBuilder()
				.setPlatform(platform).setAudience(audience)
				.setNotification(notifcation).build();
		try {
			reqResult = getInstance().sendPush(pushPayload);
			repResult = getInstance().getReportReceiveds(String.valueOf(reqResult.msg_id)) ;
			  List<ReceivedsResult.Received> list = new ArrayList<ReceivedsResult.Received>() ;
              list = repResult.received_list ;
              for(ReceivedsResult.Received var :list){
              		 pushNumber = var.android_received + var.ios_apns_sent + var.ios_msg_received + var.wp_mpns_sent ;
              }
			
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}finally{
			//保存推送信息
		/*	pushDetail.setID("585858585");
			pushDetail.setDeviceToken(pd.getString("REGISTRATION_ID"));
			pushDetail.setPUSH_TIME(DateUtil.getTime());
			pushDetail.setAcceptState(String.valueOf(pushNumber));
			pushDetail.setSUCCESS_STATE(reqResult.isResultOK());
			pushDetail.setPUSH_CONTENT(pd.getString("alert"));
			pushDetail.setPUSH_STATE(reqResult.getResponseCode()==200?0:1);
			pushDetail.setMASTER_CODE(String.valueOf(reqResult.msg_id));
			pushDetailService.save(pushDetail); */
			pd.put("PUSH_TIME", DateUtil.getTime());
			pd.put("AcceptState", String.valueOf(pushNumber));
			pd.put("SUCCESS_STATE", reqResult.isResultOK());
			pd.put("PUSH_STATE", reqResult.getResponseCode()==200?0:1);
			pd.put("MASTER_CODE",String.valueOf(reqResult.msg_id));
			pd.put("RECEIVE_CODE", String.valueOf(reqResult.sendno));
			pushDetailService.save(pd) ;
		}
		
		return new Gson().toJson(reqResult);
	}

	public static void main(String[] args) {
	/*	PageData pd = new PageData() ;
		pd.put("alert","hello join ") ;
		pd.put("title", "im mali") ;
		pd.put("REGISTRATION_ID", "9568424158");
		 try {
			 pushMsgToRegistrationId(pd);
		} catch (Exception e) {
			e.printStackTrace();
		}*/

	}
}
